package 作业.从第一个题改编抽奖箱;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class MyRunnable implements Runnable{
    public List<Integer> num= new ArrayList<>();
     public  List<Integer> list1= new ArrayList<>();
     public  List<Integer> list2= new ArrayList<>();

    public MyRunnable() {
        Collections.addAll(num,1,2,3,4,5,6,7,8,9,10,11,12);
    }

    @Override
    // 重写run()方法
    public void run() {
        // 无限循环
        while (true){

            // 如果发送礼物成功，则跳出循环
            if (sendGift()){
                break;
            }

            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    private synchronized boolean sendGift(){
        Random random = new Random();
        if (num.size()>0){
            int index = random.nextInt(num.size());

            if(Thread.currentThread().getName().equals("抽奖箱1")){
                list1.add(num.get(index));
            }else{
                list2.add(num.get(index));
            }

            System.out.println(Thread.currentThread().getName()+"正在抽奖:"+num.get(index));

            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            num.remove(index);
            return false;
        }else {

            return true;
        }
    }
}
